import Cache from "@/utils/cache.js";
import {
	emailToLogin,
	getUserInfo,
	logout
} from "@/api/user.js";
import {
	message
} from "@/utils/tools.js";

const user = {
	// 开启命名空间
	namespaced: true, 
    state: {
		token: Cache.getToken() || "",
		info: null,
		uid: null,
		authorities: [],
		bind: []
	},
    mutations: {
		// 设置token
		SET_TOKEN(state, token) {
			Cache.setToken(token);
			state.token = token;
		},
		// 设置info
		SET_INFO(state, info) {
			state.info = info
		},
		LOGOUT(state) {
			// Cache.clear('info');
			Cache.clearToken();
			state.info = null;
			state.authorities = [];
			state.bind = [];
			state.uid = null;
		},
		SET_AUTHORITIES(state, authorities) {
			state.authorities = authorities;
		},
		SET_BIND(state, bind) {
			state.bind = bind;
		},
		SET_UID(state, uid) {
			state.uid = uid;
		}
	},
    actions: {
		// 登录
		login({state, commit, dispatch}, playload) {
			return new Promise((resolve, reject) => {
				// 结构用户信息与token
				const {type} = playload;
				// 邮箱登录
				if(type === "email") {
					const {email, password, loginCode:code} = playload
					return dispatch("loginByEmail", {email, password, code})
					.then(res => resolve(res))
					.catch(err => reject(err));
				}
				reject();
			})
		},
		// 邮箱登录
		loginByEmail({state, commit, dispatch}, playload) {
			return new Promise((resolve, reject) => {
				emailToLogin(playload).then(res => {
					commit("SET_TOKEN", res.token);
					dispatch("getUserInfo");
					resolve();
				}).catch(err => {
					reject(err);
				})
			})
		},
		// 获取用户信息
		getUserInfo({state, commit}) {
			return new Promise((resolve, reject) => {
				getUserInfo().then(res => {
					commit("SET_INFO", res.user);
					commit("SET_UID", res.user.id);
					commit("SET_AUTHORITIES", res.authorities);
					commit("SET_BIND", res.bind);
					resolve();
				}).catch(err => {
					message(err.message)
					reject(err);
				})
			});
		},
		// 退出登录
		logout({commit}) {
			return new Promise((resolve, reject) => {
				logout().then(res => {
					commit("LOGOUT");
					message("注销登录成功！");
					// 发现问题，要清除前置页面
					Cache.clearBackUrl();
					resolve();
				}).catch(err => {
					// message(err.message);
					reject(err);
				})
			})
		}
	},
	getters: {
		autoGetInfo(state) {
			return state.token && state.info
		}
	}
}

export default user;